package com.xqnode.boot.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.xqnode.boot.common.JsonResult;
import com.xqnode.boot.dao.UserDao;
import com.xqnode.boot.entity.User;
import com.xqnode.boot.exception.BusinessException;
import com.xqnode.boot.model.UserDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * created by xiaqing on 2019/3/6 20:11
 */
@Api(tags = "用户相关接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserDao userDao;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public JsonResult login(@ApiParam(name = "用户请求实体")
                            @RequestBody UserDTO userDTO) throws BusinessException {
        String loginName = userDTO.getLoginName();
        String passwordMd5 = SecureUtil.md5(userDTO.getPassword());
        User user = userDao.findUserByLoginNameAndPassword(loginName, passwordMd5);
        if (user == null) {
            throw new BusinessException("用户名或密码错误");
        }
        return JsonResult.dataResult("登录成功");
    }

    @ApiOperation("用户注册")
    @PostMapping("/registry")
    public JsonResult registry(@ApiParam(name = "用户请求实体")
                               @RequestBody UserDTO userDTO) throws BusinessException {
        if (StrUtil.isBlank(userDTO.getLoginName()) || StrUtil.isBlank(userDTO.getPassword())) {
            throw new BusinessException("用户名和密码不能为空");
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setPassword(SecureUtil.md5(userDTO.getPassword()));
        user.setCreateTime(new Date());
        userDao.save(user);
        return JsonResult.dataResult(user);
    }
}
